package de.heimlich.gut;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RemoteViews;

public class ConfigurationActivity extends Activity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener{
	private int widgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	
	private int layout = R.layout.main;
	private int show = R.id.config_show_inbox;
	private int tap = R.id.config_tap_popup;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		this.setContentView(R.layout.config_activity_layout);

		widgetId = getIntent().getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
		setConfigureResult(Activity.RESULT_CANCELED);
        if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
            return;
        }
        ((RadioGroup)findViewById(R.id.config_show_radio_group)).setOnCheckedChangeListener(this);
        ((RadioGroup)findViewById(R.id.config_tap_radio_group)).setOnCheckedChangeListener(this);
        ((RadioGroup)findViewById(R.id.config_theme_radio_group)).setOnCheckedChangeListener(this);
        ((Button)findViewById(R.id.config_apply_button)).setOnClickListener(this);
	}
	
    /**
     * Convenience method to always include {@link #mAppWidgetId} when setting
     * the result {@link Intent}.
     */
    public void setConfigureResult(int resultCode) {
        final Intent data = new Intent();
        data.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
        setResult(resultCode, data);
    }

	public void onClick(View v) {
		if(v.getId() == R.id.config_apply_button) {
			WidgetPreferences prefs = new WidgetPreferences(getBaseContext());
			prefs.setLayout(layout, widgetId);
			prefs.setShow(show, widgetId);
			prefs.setTapBehavior(tap, widgetId);
			
			MessagesProvider.doBuildUpdate(getBaseContext(), 
					SmsPopupUtils.getLastSmsFromInbox(getBaseContext()), layout, widgetId);
			

			Intent resultValue = new Intent();
			resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
			setResult(RESULT_OK, resultValue);
			finish();
		}
		
	}

	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// TODO Auto-generated method stub
		switch(group.getId()) {
		case R.id.config_show_radio_group:
			show = checkedId;
			break;
		case R.id.config_tap_radio_group:
			tap = checkedId;
			break;
		case R.id.config_theme_radio_group:
			if(checkedId == R.id.config_theme_classic)
				layout = R.layout.main;
			else
				layout = R.layout.vista_style;
			break;
		}
	}
}
